const ol = require("ol3");
const Tile = require("../Tile");
const React = require("react");
const StripeData = require("../../../data/data");

var styles = [
    /* We are using two different styles for the polygons:
     *  - The first style is for the polygons themselves.
     *  - The second style is to draw the vertices of the polygons.
     *    In a custom `geometry` function the vertices of a polygon are
     *    returned as `MultiPoint` geometry, which will be used to render
     *    the style.
     */
    new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'blue',
            width: 3
        }),
        fill: new ol.style.Fill({
            color: 'rgba(0, 0, 255, 0.1)'
        })
    })
];

const InitPage = React.createClass({

    renderPolygons(){
        var features = StripeData.map(function(item){
            var wkt = item.wkt;

            var format = new ol.format.WKT();

            return format.readFeature(wkt, {
                dataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            });
        });

        var imageLayers = this.renderImages(features);

        var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            }),
            style: styles
        });

        return [vector].concat(imageLayers);
    },

    renderImages(features){
        return features.map(function(feature, index){
            var poly = feature.getGeometry();
            var item = StripeData[index];

            var imageSource = new ol.source.ImageTransform({
                url: "../data/"+item.name+"/"+item.fileURL,
                crossOrigin: '',
                projection: 'EPSG:3857',
                imageExtent: poly.getExtent(),
                targetPolygon: poly,
                direction: "right_up"//ol.source.ImageTransform.DIRECTION.RIGHT_UP
            });

            return new ol.layer.Image({
                source: imageSource
            });
        });
    },

    componentDidMount(){
        var layers = this.renderPolygons();

        var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ].concat(layers),
            view: new ol.View({
                center: ol.proj.fromLonLat([116,41]),
                zoom: 4
            })
        });
    },

    render(){
        return (
            <div className="container">
                <Tile header="旋转">
                    <div id="map">

                    </div>
                </Tile>
            </div>
        );
    }
});

module.exports = InitPage;